/**
 * 易驰护运 - Vip
 * http://menger.me
 * 会员中心
 * @桓桓
 */

'use strict';

import React from 'react'
import { StyleSheet, Text, ScrollView, TouchableOpacity, ImageBackground, View, Keyboard, ImageStore} from 'react-native';
import {
    IconFont,
    ListView,
    VerticalLine,
    HorizontalLine,
    BannerComponent,
    HotNewsComponent,
    HomeResourceItem,
    ListHeaderLoading,
} from '../../components';
import {inject, observer} from 'mobx-react';
import VipItem from '../../components/customer/Item/VipItem';

@inject('loginStore')
@observer
export default class Vip extends React.Component {

    constructor(props) {
        super(props);
        this.params = this.props.navigation.state.params;
        this.state = {
            loading: true,
            dataSources: [],
            userInfo: {},
        }
        this.page = 1;
        this.limit = 10;
    }

    componentDidMount() {
        this._requestDataSources();
    }

    componentWillUnmount() {
        this.timerArray = [this.stopLoadingTimer];
        ClearTimeOut(this.timerArray);
    }

    _requestDataSources = async () => {
        let { dataSources } = this.state;
        let url = ServicesApi.PERSONAL_CENTER_MEMBER_CENTER;
        let data = {
            page: this.page,
            limit: this.limit,
        };
        try {
            const result = await Services.post(url, data);
            let dataSourceTemp = dataSources.slice();
            let dataList = [];
            if (result.code === StatusCode.SUCCESS_CODE) {
                dataList = result.data.point_log.dataList || [];
                if (parseInt(data.page) === 1) {
                    dataSourceTemp = dataList
                } else {
                    if (dataList.length !== 0) {
                        dataSourceTemp = dataSourceTemp.concat(dataList);
                    }
                }
            }
            this.setState({ 
                userInfo: result.data.member_info,
                dataSources: dataSourceTemp,
                loading: false,
            });
            this._onStopLoading(dataList.length < this.limit);
        } catch (error) {
            this._onStopLoading(true);
        }
    };

    // 下拉刷新
    _onRefresh = () => {
        this.page = 1;
        this._requestDataSources();
    };

    // 结束加载
    _onStopLoading = (status = true) => {
        this.stopLoadingTimer = setTimeout(() => this.setState({ loading: false, ready: true }), 500);
        this._listRef && this._listRef.stopRefresh();
        this._listRef && this._listRef.stopEndReached({ allLoad: status });
    };

    // 上拉加载
    _onEndReached = () => {
        this.page++;
        this._requestDataSources();
    }

    // 定义 refs
    _captureRef = (v) => {
        this._listRef = v
    };

    // 生成 Key
    _keyExtractor = (item, index) => {
        return `item_${index}`
    };

    _renderItem = ({item, index}) => {
        return (
            <VipItem
                item={item}
                {...this.props}
            />
        );
    };

    renderListHeaderComponent = () => {
        let {userInfo} = this.state;
        return (
            <View>
                <View style={styles.header}>
                    {/* <ImageView
                        resizeMode={'cover'}
                        style={styles.headerBg1}
                        source={Images.img_vip_bg1}
                    /> */}
                    <ImageBackground style={styles.headerBg2} source={Images.img_vip_bg2} resizeMode={'contain'}>
                        <View style={styles.userInfo}>
                            <ImageView
                                resizeMode={'cover'}
                                style={styles.userInfoImg}
                                source={{uri: userInfo.avatar}}
                            />
                            <View style={styles.userInfoRight}>
                                <Text style={styles.userInfoName} numberOfLines={1}>{userInfo.nickname}</Text>
                                <View style={styles.userInfoVipLevelBox}>
                                    <Text style={styles.userInfoVipLevel} numberOfLines={1}>{userInfo.member_level_text}</Text>
                                </View>
                            </View>
                        </View>
                        <Text style={styles.integral}>积分数量：{userInfo.total_member_point}</Text>
                    </ImageBackground>
                    <View style={{height: 50, backgroundColor: '#fff'}}/>
                </View>    
                <View style={styles.center}>
                    <View style={styles.centerBall}><View style={styles.centerBallCenter}/></View>
                    <Text style={styles.centerText} numberOfLines={1}>积分获取记录</Text>
                </View>
            </View>
        )
    }

    ItemSeparatorComponent = () => {
        return <View style={{height: Predefine.minPixel, backgroundColor: '#f2f2f2', marginHorizontal: 15}}/>
    }

    render() {
        let {loading, dataSources} = this.state;
        return (
            <PageContainer loading={loading} style={styles.container}>
                <NavigationBar
                    title={'会员中心'}
                    style={[styles.navigationBarStyle]}
                    renderRightAction={[{
                        title: <Text style={{color: '#fff', fontSize: 13}}>等级规则</Text>, 
                        onPress: () => RouterHelper.navigate('', 'Level')
                    }]}
                />
                <ListView
                    data={dataSources}
                    ref={this._captureRef}
                    extraData={this.state}
                    style={styles.listContent}
                    onRefresh={this._onRefresh}
                    renderItem={this._renderItem}
                    keyExtractor={this._keyExtractor}
                    onEndReached={this._onEndReached}
                    ItemSeparatorComponent={this.ItemSeparatorComponent}
                    ListHeaderComponent={() => this.renderListHeaderComponent()}
                />
            </PageContainer>
        );
    }
}

const HeaderHeight = SCREEN_WIDTH*(844/1488);
const DominantColor = '#00BFCC';
const styles = StyleSheet.create({
    container: {
        backgroundColor: '#F0F0F0'
    },

    header: {
        height: HeaderHeight,
    },
    headerBg1: {
        width: SCREEN_WIDTH,
        height: HeaderHeight - 50,
    },
    headerBg2: {
        width: SCREEN_WIDTH,
        height: HeaderHeight,
        zIndex: 1,
        position: 'absolute',
        top: 10,
        paddingLeft: 50,
        paddingVertical: 40,
        justifyContent: 'space-between',
    },

    userInfo: {
        flexDirection: 'row',
    },
    userInfoImg: {
        width: 46,
        height: 46,
        borderRadius: 23,
        marginRight: 10,
        backgroundColor: '#f2f2f2',
    },
    userInfoRight: {
        justifyContent: 'space-between',
    },
    userInfoName: {
        fontSize: 18,
        color: '#664630',
        fontWeight: 'bold',
    },
    userInfoVipLevelBox: {
        backgroundColor: '#EED09A',
        borderRadius: 10,
        paddingHorizontal: 6,
        height: 20,
        justifyContent: 'center',
        alignItems: 'center',
    },
    userInfoVipLevel: {
        fontSize: 12,
        color: '#664630',
    },
    integral: {
        color: '#A97835',
        fontSize: 20,
    },
    
    // 中间部分
    center: {
        flexDirection: 'row',
        alignItems: 'center',
        height: 40,
        paddingHorizontal: 15,
    },
    centerBall: {
        width: 12,
        height: 12,
        borderRadius: 6,
        backgroundColor: DominantColor,
        marginRight: 6,
        alignItems: 'center',
        justifyContent: 'center',
    },
    centerBallCenter: {
        height: 6,
        width: 6,
        borderRadius: 3,
        backgroundColor: '#F0F0F0',
    },
    centerText: {
        color: '#333',
        fontSize: 13,
        fontWeight: 'bold',
    },
});